//
//  TableViewContentInsetViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2019/10/9.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "TableViewContentInsetViewController.h"
#import <HBDNavigationBar/UIViewController+HBD.h>
#import <MJRefresh/MJRefresh.h>

#define minHeaderHeight 120

@interface TableViewContentInsetViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) UIView *headerBarView;
@property (nonatomic, strong) UILabel *headerBarLabel;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation TableViewContentInsetViewController {
    
    CGFloat _gradientProgress;
}

- (void)loadView {
    
    [super loadView];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.view = tableView;
    self.tableView = tableView;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    header.automaticallyChangeAlpha = YES;
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 马上进入刷新状态
    [header beginRefreshing];
    // 设置header
    self.tableView.mj_header = header;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNextData)];
    self.tableView.mj_footer = footer;
}
    
- (void)loadNewData {
    
    NSLog(@"%s",__func__);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}
    
- (void)loadNextData {
    
    NSLog(@"%s",__func__);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_footer endRefreshing];
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Dynamic Gradient Bar";
    
    UITableView *tableView = self.tableView;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    if (@available(iOS 11,*)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"lakeside_sunset" ofType:@"png"];
    UIImage *headerImage = [UIImage imageWithContentsOfFile:imagePath];
   
    _headerView = [[UIImageView alloc] initWithImage:headerImage];
    _headerView.clipsToBounds = YES;
    _headerView.contentMode = UIViewContentModeScaleAspectFill;
    _headerView.userInteractionEnabled = YES;
    [self.view insertSubview:_headerView aboveSubview:tableView];
    
    //cxx_test
    [_headerView addSubview:self.headerBarView];
    [_headerView addSubview:self.headerBarLabel];
    [_headerView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
    
//    self.hbd_barHidden = YES; //cxx_test
    self.hbd_barAlpha = 0.0;
    self.hbd_barStyle = UIBarStyleBlack;
    self.hbd_tintColor = UIColor.whiteColor;
    self.hbd_titleTextAttributes = @{ NSForegroundColorAttributeName: [UIColor.whiteColor colorWithAlphaComponent:0.0] };
}

- (void)dealloc {
    
    [_headerView removeObserver:self forKeyPath:@"frame"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([@"frame" isEqualToString:keyPath]) {
        CGRect frame = _headerView.bounds;
        if (CGRectGetHeight(frame) == minHeaderHeight) {
            self.headerBarView.alpha = 0;
        } else {
            self.headerBarView.alpha = 1.0;
        }
        frame.origin.y = CGRectGetHeight(frame)-50;
        frame.size.height = 50;
        
        self.headerBarView.frame = frame;
        self.headerBarLabel.frame = frame;
    }
}

- (void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    UITableView *tableView = self.tableView;
    UIImageView *headerView = self.headerView;
    
    CGFloat width = CGRectGetWidth(self.view.bounds);
    UIImage *headerImage = headerView.image;
    CGFloat imageHeight = headerImage.size.height / headerImage.size.width * width;
    CGRect headerFrame = headerView.frame;
    
    if (tableView.contentInset.top == 0) {
        UIEdgeInsets inset = UIEdgeInsetsZero;
        if (@available(iOS 11,*)) {
            inset.bottom = self.view.safeAreaInsets.bottom;
        }
        tableView.scrollIndicatorInsets = inset;
        inset.top = imageHeight;
        tableView.contentInset = inset;
        tableView.contentOffset = CGPointMake(0, -inset.top);
    }
    
    if (CGRectGetHeight(headerFrame) != imageHeight) {
        headerView.frame = [self headerImageFrame];
    }
}

- (CGRect) headerImageFrame {
    
    UITableView *tableView = self.tableView;
    UIImageView *headerView = self.headerView;
    
    CGFloat width = CGRectGetWidth(self.view.bounds);
    UIImage *headerImage = headerView.image;
    CGFloat imageHeight = headerImage.size.height / headerImage.size.width * width;
    
//    CGFloat contentOffsetY = tableView.contentOffset.y + tableView.contentInset.top;
//    if (contentOffsetY < 0) {
//        imageHeight += -contentOffsetY;
//    }
//    CGRect headerFrame = self.view.bounds;
//    if (contentOffsetY > 0) {
//        headerFrame.origin.y -= contentOffsetY;
//    }
//    headerFrame.size.height = imageHeight;
    
    CGRect headerFrame = self.view.bounds;
    CGFloat contentOffsetY = tableView.contentOffset.y + tableView.contentInset.top;
    if (contentOffsetY < 0) {
        //imageHeight += -contentOffsetY;
        
    } else {
        if (tableView.contentOffset.y>-1*minHeaderHeight) {
            imageHeight = minHeaderHeight;
        } else {
            imageHeight = fabs(tableView.contentOffset.y);
        }
    }
    headerFrame.size.height = imageHeight;
    
    return headerFrame;
}

- (UIView *)headerBarView {
    
    if (!_headerBarView) {
        _headerBarView = [[UIView alloc] init];
        _headerBarView.backgroundColor = [UIColor clearColor];
    }
    return _headerBarView;
}

- (UILabel *)headerBarLabel {
    
    if (!_headerBarLabel) {
        _headerBarLabel = [[UILabel alloc] init];
        _headerBarLabel.font = [UIFont boldSystemFontOfSize:30];
        _headerBarLabel.text = @"  头部";
        _headerBarLabel.textColor = [UIColor whiteColor];
    }
    
    return _headerBarLabel;
}

- (void) popToRoot:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UITableViewDelegate

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"demo"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 30;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"click me %d",(int)indexPath.row];
    return cell;
}

- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat headerHeight = CGRectGetHeight(self.headerView.frame);
    if (@available(iOS 11,*)) {
        headerHeight -= self.view.safeAreaInsets.top;
    } else {
        headerHeight -= [self.topLayoutGuide length];
    }
    
    CGFloat progress = scrollView.contentOffset.y + scrollView.contentInset.top;
    CGFloat gradientProgress = MIN(1, MAX(0, progress  / headerHeight));
    gradientProgress = gradientProgress * gradientProgress * gradientProgress * gradientProgress;
    if (gradientProgress != _gradientProgress) {
        _gradientProgress = gradientProgress;
        if (_gradientProgress < 0.1) {
            self.hbd_barStyle = UIBarStyleBlack;
            self.hbd_tintColor = UIColor.whiteColor;
            self.hbd_titleTextAttributes = @{ NSForegroundColorAttributeName: [UIColor.blackColor colorWithAlphaComponent:0] };
        } else {
            self.hbd_barStyle = UIBarStyleDefault;
            self.hbd_tintColor = UIColor.blackColor;
            self.hbd_titleTextAttributes = @{ NSForegroundColorAttributeName: [UIColor.blackColor colorWithAlphaComponent:_gradientProgress] };
        }
        
        self.hbd_barAlpha = _gradientProgress;
        [self hbd_setNeedsUpdateNavigationBar];
    }
    self.headerView.frame = [self headerImageFrame];
}

@end
